import HttpServe from './httpServe';
import { Loading, Message } from 'element-ui';
import store from '@/store';
import * as auth from '@/utils/auth';
import router from '../router';

let loadingInstance = null;

const http = new HttpServe({
  // 使用统一的catch 如果不想使用可以 http.get().catch_http_error() 即可以自己catch
  onNetworkError(err) {
    const { errMessage } = err;
    Message({
      type: 'error',
      message: `${errMessage}`,
    });
    return;
  },

  async beforeSend(request) {
    request.headers = Object.assign(request.headers, {
      token: auth.getToken(),
    });
  },

  // 统一处理code码错误， 如果不想使用 dispose_server_error() 可以自己处理
  async onServerError(error_data) {
    console.log('code码错误', error_data);
    const { errMessage, errCode } = error_data;

    if (errCode === '401') {
      Message({
        type: 'warning',
        message: `${errMessage}`,
      });
      await store.dispatch('user/logout');
      router.push(`/login?redirect=${router.history.current.fullPath}`);
      return;
    }

    Message({
      type: 'error',
      message: `${errMessage}`,
    });
    return;
  },

  defaultLoading: {
    show() {
      // console.log(store.getters.customerId, 'storestorestore')
      loadingInstance = Loading.service({ fullscreen: true });
    },
    hide() {
      loadingInstance.close();
    },
  },
});

export default http;
